package config

import (
	"errors"
	"sync"
)

const BalancerRoundRobin = "roundRobinBalancer"

// GetBalancer 创建负责均衡器， 统一入口
func GetBalancer(balancerName string, serverList []string) Balancer {
	var balancer Balancer
	switch balancerName {
	case BalancerRoundRobin:
		balancer = getRoundRobinBalancer(serverList)
	default:
		balancer = nil
	}
	return balancer
}

// Balancer 负责均衡接口， 负载均衡器需要实现该Select方法，客户端调用select 方法可以获取到服务列表
type Balancer interface {
	Select() (string, error)
}

type RoundRobinBalancer struct {
	index      int
	serverList []string
	mu         sync.Mutex
}

func getRoundRobinBalancer(serverList []string) *RoundRobinBalancer {
	return &RoundRobinBalancer{
		index: 0, serverList: serverList,
	}
}

func (r *RoundRobinBalancer) Select() (string, error) {
	if len(r.serverList) == 0 {
		return "", errors.New("暂无服务可用")
	}
	r.mu.Lock()
	defer r.mu.Unlock()
	serverName := r.serverList[r.index]
	r.index = (r.index + 1) % len(r.serverList)
	return serverName, nil
}
